package dk
{
	import flash.events.*;
	import flash.media.Camera;
	import flash.media.Video;
	import flash.utils.Timer;
	
	public class MotionDetect
	{
		private var vid:Video;
		private var delayTimer:Number = 100;
		[Bindable]
		public var cam:Camera;
		private var timer:Timer;
		[Bindable]
		private var camW:int = 320;
		[Bindable]
		private var camH:int = 240;
		[Bindable]
		private var camF:Number = 5;
		[Bindable]
		private var camT:Number=2000;
		[Bindable]
		private var camM:int = 20;
		
		public function MotionDetect()
		{
			//trace("Motion Dectect constructor()");
			//cam = Camera.getCamera();
			startChecking();
		}
		
		private function startChecking():void
		{
			if (timer==null)
			{
				timer = new Timer(delayTimer);
				timer.addEventListener(TimerEvent.TIMER, timerEventHandler);
			}
			timer.start(); 
		}
		
		private function stopChecking():void 
		{
			if(timer != null && timer.running) 
			{
				timer.stop();
			}
		}
		
		private function timerEventHandler(event:TimerEvent):void
		{
			cameraCheck();
		}
		
		private function cameraCheck():void
		{
			//check have camera or not
			if (cam != null) 
			{
				trace("Found a cam!");
                cam.setMode(camW, camH, camF);
				cam.setMotionLevel(camM, camT);
				stopChecking();
				
				//start Motion Detecting
				startDetecting();
            } 
            else 
            {
                trace("Checking camera...");
            }
        }
        
        public function startDetecting():void
		{
			trace("function: startDetecting()");
			if (cam != null) {
                cam.addEventListener(ActivityEvent.ACTIVITY, activityHandler);
                vid = new Video(cam.width * 2, cam.height * 2);
                vid.attachCamera(cam);
                //addChild(vid);
            } else {
                trace("You need a camera.");
                startChecking();
            }
		}
		
        public function activityHandler(event:ActivityEvent):void {
            //trace("activityHandler: " + event);
            if (event.activating)
            {
            	trace("Motion detected!!! Motion: "+cam.activityLevel);
            }
            else
            {
            	trace("no more motioning.");
            }
		}

	}
}